package by.grsu.vashchilo.page;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.Model;

import by.grsu.vashchilo.app.AirlineWebApplication;
import by.grsu.vashchilo.dao.impl.UserDao;
import by.grsu.vashchilo.entity.User;
import by.grsu.vashchilo.entity.UserRole;
import by.grsu.vashchilo.page.HomePage;
import by.grsu.vashchilo.page.administrator.AdministratorPage;
import by.grsu.vashchilo.page.client.UserPage;

public class HomePage extends WebPage {
	@SuppressWarnings({ "unchecked", "serial" })
	public HomePage() {
		super();
		final Form form = new Form("form");
		add(form);

		final TextField login = new TextField("login", new Model());
		final TextField password = new TextField("password", new Model());

		form.add(login);
		form.add(password);

		form.add(new SubmitLink("ok") {
			@Override
			public void onSubmit() {
				super.onSubmit();
				try {
					UserDao userDao = new UserDao(
							AirlineWebApplication.DATA_XML_FOLDER);
					User user = userDao.searchByLogin(login.getValue());
					if (user.getUserRole().equals(UserRole.administrator)) {
						if (user.getPassword().equals(password.getValue())) {
							setResponsePage(new AdministratorPage(user));

						} else {
							setResponsePage(new HomePage());
						}
					} else {
						if (user != null) {
							if (user.getPassword().equals(password.getValue())) {
								setResponsePage(new UserPage(user));

							} else {
								setResponsePage(new HomePage());
							}
						}
					}
				} catch (Exception ex) {

				}
			}
		});

		form.add(new Link("cancel") {
			@Override
			public void onClick() {
				setResponsePage(new HomePage());
			}
		});

	}
}
